<template>
  <div>
    <section class="filter">
      <div class="filter-container">
        <el-form ref="form" :inline="true">
          <el-form-item label="搜索内容：">
            <el-input
              v-model="listQuery.title"
              placeholder="请输入内容标题"
              class="filter-item"
              clearable
              @input="resetPage"
            />
          </el-form-item>
          <el-form-item label="选择类型：">
            <el-radio-group v-model="listQuery.status" @change="resetPage">
              <el-radio v-for="(item, index) in tempStateList" :key="index" :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
    </section>

    <section class="result">
      <el-table
        :data="list"
        :header-cell-style="{textAlign: 'center', fontWeight: '600'}"
        :cell-style="{textAlign: 'center'}"
        highlight-current-row
      >
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column label="标题">
          <template slot-scope="scope">
            <span>{{ scope.row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="作者">
          <template slot-scope="scope">
            <span>{{ scope.row.authorName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型">
          <template slot-scope="scope">
            <span>{{ typeList.find((item) => { return item.value === scope.row.type }).label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="标签">
          <template slot-scope="scope">
            <span>{{ scope.row.labels }}</span>
          </template>
        </el-table-column>
        <el-table-column label="定时时间">
          <template slot-scope="scope">
            <span>{{ scope.row.publishTime | dateTimeFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            <span>{{ scope.row.createdTime | dateTimeFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="提交时间">
          <template slot-scope="scope">
            <span>{{ scope.row.submitedTime | dateTimeFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <span v-if="!type">{{ stateList.find((item) => { return item.value === scope.row.status }).label }}</span>
            <span v-else>{{ stateList.find((item) => { return item.value === scope.row.enable }).label }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              type="text"
              class="el-button--success-text"
              @click="goToDetailView(scope.row)"
            >查看</el-button>
            <template v-if="!type">
              <el-button
                type="text"
                class="el-button--primary-text"
                :disabled="scope.row.status !== 3"
                @click="operateForPass(scope.row.id)"
              >通过</el-button>
              <el-button
                type="text"
                class="el-button--danger-text"
                :disabled="scope.row.status !== 3"
                @click="operateForFail(scope.row.id)"
              >驳回</el-button>
            </template>
            <template v-else>
              <el-button
                type="text"
                class="el-button--primary-text"
                :disabled="scope.row.enable === 1"
                @click="operateForDownOrUp(scope.row.id, 1)"
              >上架</el-button>
              <el-button
                type="text"
                class="el-button--danger-text"
                :disabled="scope.row.enable === 0"
                @click="operateForDownOrUp(scope.row.id, 0)"
              >下架</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </section>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.size" @pagination="getList" />
  </div>
</template>

<script>
import Pagination from '@/components/pagination'
import { authList, authPass, authFail, downOrUp } from '@/api/news'

// 审核状态
const statusList = [
  {
    label: '全部',
    value: undefined,
    hidden: false
  },
  {
    label: '待人工审核',
    value: 3,
    hidden: false
  },
  {
    label: '人工审核通过',
    value: 4,
    hidden: false
  },
  {
    label: '审核失败',
    value: 2,
    hidden: false
  },
  {
    label: '已发布',
    value: 9,
    hidden: false
  },
  {
    label: '草稿',
    value: 0,
    hidden: true
  },
  {
    label: '提交（待审核）',
    value: 1,
    hidden: true
  },
  {
    label: '审核通过（待发布）',
    value: 8,
    hidden: true
  }
]
// 上架状态
const enableList = [
  { label: '全部', value: '' },
  { label: '正常', value: 1 },
  { label: '已下架', value: 0 }
]

export default {
  name: 'NewsList',
  components: { Pagination },
  data () {
    return {
      type: 0, // 0媒体审核 1内容管理
      stateList: [],
      typeList: [
        {
          value: 0,
          label: '无图文章'
        },
        {
          value: 1,
          label: '单图文章'
        },
        {
          value: 3,
          label: '多图文章'
        }
      ],
      // 列表相关
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        title: undefined,
        status: undefined,
        page: 1,
        size: 10
      }
    }
  },
  computed: {
    tempStateList () {
      return this.stateList.filter((item) => { return !item.hidden })
    }
  },
  created () {
    this.type = parseInt(this.$route.params.type, 10)
    this.stateList = !this.type ? statusList : enableList
    this.getList()
  },
  methods: {
    async getList () {
      // el-input和el-select执行clear后值为''，主动转换为undefined
      if (this.listQuery.title === '') {
        this.listQuery.title = undefined
      }

      const res = await authList(this.listQuery)
      if (res.code === 200) {
        this.list = res.data
        this.total = res.total
      } else {
        this.$message({ type: 'error', message: res.error_message })
      }
    },
    // 重置分页page
    resetPage () {
      this.listQuery.page = 1
      this.getList()
    },
    // 查看详情
    goToDetailView (row) {
      // TODO: 跳转页面，左边侧栏状态丢失
      this.$router.push({
        path: '/news/detail',
        query: {
          id: row.id
        }
      })
    },
    // 通过/驳回
    async operateForPass (id) {
      const res = await authPass({ id: id, status: 4 })
      if (res.code === 0) {
        this.getList()
        this.$message({ type: 'success', message: '操作成功！' })
      } else {
        this.$message({ type: 'error', message: res.errorMessage })
      }
    },
    operateForFail (id) {
      this.open('请输入驳回理由', { id: id, status: 2 })
    },
    open (msg, params) {
      this.$prompt(undefined, '驳回理由', {
        confirmButtonText: '提交',
        confirmButtonClass: 'el-button--success',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--warning',
        inputPlaceholder: msg,
        inputType: 'textarea'
      }).then(async ({ value }) => {
        // TODO: 驳回理由为空的情况
        params.msg = value
        const res = await authFail(params)

        if (res.code === 0) {
          this.getList()
          this.$message({ type: 'success', message: '操作成功！' })
        } else {
          this.$message({ type: 'error', message: res.errorMessage })
        }
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消驳回' })
      })
    },
    // 上架/下架
    async operateForDownOrUp (id, enable) {
      const res = await downOrUp({ id: id, enable: enable })

      if (res.code === 0) {
        this.getList()
        this.$message({ type: 'success', message: '操作成功！' })
      } else {
        this.$message({ type: 'error', message: res.errorMessage })
      }
    }
  }
}
</script>
